package com.thinkgem.jeesite.common.utils;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;


public class XMLUtil {
	/**
	 * dom4j方式
	 * @param file
	 * @return
	 */
	public static void parse(File file,String dest) {
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			document = reader.read(file);
			String firstString = document.asXML();
			if (!StringUtils.isBlank(firstString)) {
				//处理
				firstString = replaceBlank(firstString);
				firstString = replace(firstString);
				firstString.replace("&", "&#38;");
				firstString.replace("<", "&#60;");
				firstString.replace(">", "&#62;");
			}
			//删除旧文件
			File destFile = new File(dest);
			if (destFile.exists()) {
				destFile.delete();
			}
			//创建文件夹
			if (!destFile.getParentFile().exists()) {
				destFile.getParentFile().mkdirs();
			}
			FileUtils.writeToFile(dest, firstString, false);
			//FileUtils.writeToFile(dest+".xml", firstString, false);
			if (file.exists()) {
				file.delete();
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	public static String replaceBlank(String str) {
		String dest = "";
		if (str!=null) {
			Pattern p = Pattern.compile("\f|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}
	
	public static void main(String[] args){
		parse(new File("C:\\Users\\fanqinglong\\Desktop\\新建 Microsoft Word 文档.xml"), "C:\\Users\\fanqinglong\\Desktop\\项目资料\\模板\\result.xml");
	}
	
	public static String replace(String inputString){
		Pattern pattern = Pattern.compile("\\$\\{[^{}]+?\\}");
		Matcher matcher = pattern.matcher(inputString);
		StringBuffer stringBuffer = new StringBuffer();
		while (matcher.find()) {
			//替换掉html标记
			String result = matcher.group(0).replaceAll("<[^<>]+>", "");
			//提取出占位符
			result = result.replace("${", "").replace("}", "");
			matcher.appendReplacement(stringBuffer, "FQL_CHAR_DOLLAR\\{"+result+"\\?html\\}");
		}
		matcher.appendTail(stringBuffer);
		return stringBuffer.toString().replace("FQL_CHAR_DOLLAR", "$");
	}
}
